package cn.stronglink.esm27.collection.iot.devices.esm27.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.stronglink.esm27.collection.core.message.IMessageHandle;
import cn.stronglink.esm27.collection.core.util.ByteUtil;
import cn.stronglink.esm27.collection.core.util.ContextUtils;
import cn.stronglink.esm27.collection.iot.devices.esm27.message.MQMessageOfESM27;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.DeviceBasePropertyEntity;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.ESM27ResponseMessageEntity;
import cn.stronglink.esm27.collection.mq.TopicSender;
import io.netty.channel.ChannelHandlerContext;

/**
 * 获取设备基本属性
 * @author yuzhantao
 *
 */
public class GetDeviceBasePropertyReturnHandle implements IMessageHandle<ESM27ResponseMessageEntity, Object> {
	private final static String ACTION_CODE="GetDeviceBasePropertyReturn";
	private final static Logger logger = LogManager.getLogger(GetDeviceBasePropertyReturnHandle.class.getName());
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	
	@Override
	public boolean isHandle(ESM27ResponseMessageEntity t) {
		if(t.getCommandCode()==0x01) {
			return true;
		}else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, ESM27ResponseMessageEntity t) {
		DeviceBasePropertyEntity deviceProperty = new DeviceBasePropertyEntity();
		deviceProperty.setDeviceAddress(t.getDeviceAddress());
		
		byte[] devId = new byte[4];
		for(int i=0;i<devId.length;i++) {
			devId[i]=t.getDatas()[devId.length-i-1];
		}
		deviceProperty.setDeviceId(ByteUtil.byteArrToHexString(devId));
		deviceProperty.setVersion(ByteUtil.bytesToUbyte(t.getDatas(),4));
		
		MQMessageOfESM27 message = new MQMessageOfESM27();
		message.setActioncode(ACTION_CODE);
		message.setTimeStamp(System.currentTimeMillis());
		message.setAwsPostdata(deviceProperty);
		message.setIsSuccess(true);
		
		String json = JSON.toJSONString(message);
		topicSender.send(json);
		logger.info("发送[{}]到MQ完成:{}","获取设备基础数据的反馈信息",json);
		return null;
	}

}

